﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;

using Microsoft.SharePoint;

namespace Eneta.Portal.Forum.Controls
{
    public class ForumsTopicsViewControl : UserControl
    {
        protected Repeater _topicsRepeater;
        protected HtmlAnchor _categoryLink;
        protected HtmlAnchor _forumLink;
        protected HtmlAnchor _newTopicLink;
        protected HtmlAnchor _rssUrl;
        protected Literal _rssUrlContents;

        protected HtmlAnchor _newTopicLinkBottom;
        protected HtmlAnchor _rssUrlBottom;
        protected Literal _rssUrlBottomContents;

        protected HtmlGenericControl pagerNextContainer;
        protected HtmlGenericControl pagerPrevContainer;
        protected HtmlAnchor pagerPrevLink;
        protected HtmlAnchor pagerNextLink;

        protected Label _forumLabel;

        private ForumRepository _forumRepository;
        private ForumRepository ForumRepository
        {
            get
            {
                if (_forumRepository != null)
                    return _forumRepository;

                _forumRepository = new ForumRepository(SPContext.Current.Web);
                return _forumRepository;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            int forumId;
            if(!int.TryParse(Request.QueryString["forum"], out forumId))
            {
                //TODO: veateade
                return;
            }

            if (!string.IsNullOrEmpty(Request.QueryString["rss"]))
            {
                Response.Clear();
                Response.ContentType = "application/rss+xml";
                Response.Write(ForumRepository.GetForumRss(forumId));
                Response.End();
                return;
            }

            if (IsPostBack)
                return;

            var forum = ForumRepository.GetForumById(forumId);
            if(forum==null)
            {
                Response.Write("forum is null");
                return;
            }



            if(_forumLink == null)
            {
                //TODO: Teha midagi
                //Response.Write("_forumLink is null");
                return;
            }
            _forumLink.HRef = string.Format(_forumLink.HRef, forum.Id);
            _forumLink.InnerText = forum.Title;
            _forumLabel.Text = forum.Title;

            _newTopicLink.HRef = string.Format(_newTopicLink.HRef, forum.Id);
            _newTopicLinkBottom.HRef = _newTopicLink.HRef;

            var category = forum.Category;

            Page.Title = Resources.Forum.ForumTitle + " > " + forum.Title + " | " + EnetaApplication.PortalTitle;

            if(category == null)
            {
                //TODO: Teha midagi
                //Response.Write("category is null");
                return;
            }
            _categoryLink.HRef = string.Format(_categoryLink.HRef, category.Id);
            _categoryLink.InnerText = category.Title;

            var rssUrl = Request.RawUrl + "&rss=1";
            if (!string.IsNullOrEmpty(forum.FeedBurnerUrl))
                rssUrl = forum.FeedBurnerUrl;

            var dto = new RssLinksDto();

            if (_rssUrl != null)
            {
                _rssUrl.HRef = rssUrl;
                _rssUrlBottom.HRef = rssUrl;

                if (_rssUrl.Controls.Count > 0 && _rssUrl.Controls[0] is Literal)
                {
                    var lit = (Literal)_rssUrl.Controls[0];
                    dto.RssTitle = lit.Text;
                }
                else
                    dto.RssTitle = _rssUrl.InnerText;
                dto.RssUrl = _rssUrl.HRef;
            }

            var master = Page.Master;
            if (master != null)
            {
                var link = (HtmlLink)master.FindControl("rssMetaUrl");
                link.Href = rssUrl;
                link.Attributes["title"] = category.Title + ": " + forum.Title;

                var typedMaster = master as MasterBaseWithDesignHack;
                if(typedMaster != null)
                {
                    dto.RssTitle = forum.Title;
                    typedMaster.SetRssLinks(dto);   
                }
            }


            var topics = ForumRepository.GetTopicsByForumId(forumId);
            topics = topics.OrderByDescending(t => t.LastPostDate).ToList();

            var page = 1;
            var pageSize = 15;
            int.TryParse(Request.QueryString["page"], out page);
            if (page < 1)
                page = 1;

            var pageCount = (int)Math.Ceiling((double)topics.Count / pageSize);
            if (page > pageCount)
                page = pageCount;

            if (Math.Max(1, page - 1) == 1)
                pagerPrevLink.HRef = _forumLink.HRef;
            else
                pagerPrevLink.HRef = _forumLink.HRef + "&page=" + Math.Max(1, page - 1);
            pagerPrevContainer.Visible = (page > 1);
            //pagerBottomPrevLink.HRef = pagerPrevLink.HRef;

            if (Math.Min(pageCount, page + 1) == 1)
                pagerNextLink.HRef = _forumLink.HRef;
            else
                pagerNextLink.HRef = _forumLink.HRef + "&page=" + Math.Min(pageCount, page + 1);
            //pagerBottomNextLink.HRef = pagerNextLink.HRef;
            pagerNextContainer.Visible = (page < pageCount);

            var topicsPage = new List<ForumTopicDto>();
            for (var i = (page - 1) * pageSize; i < Math.Min((page) * pageSize, topics.Count); i++)
            {
                topicsPage.Add(topics[i]);
            }

            _topicsRepeater.DataSource = topicsPage;
            _topicsRepeater.DataBind();            
        }

        private UserProfileRepository _profileRepository;
        public UserProfileRepository ProfileRepository
        {
            get
            {
                if (_profileRepository != null)
                    return _profileRepository;

                _profileRepository = new UserProfileRepository(SPContext.Current.Web);
                return _profileRepository;
            }
        }

        public string GetProfileImageUrl(int profileId)
        {
            var profile = ProfileRepository.GetUserProfileById(profileId);
            if (profile == null)
                return string.Empty;

            return profile.UserImage32x32Url;
        }
    }
}
